package finalproject.model.player;

import java.util.ArrayList;
import java.util.List;
/**
 * The class charged of managing the players
 * Rotate the players between as current player, allowing them to play
 * @author Buisson Kevin & Dahmoul Salah
 *
 */
public class PlayerModel {

	/** Single <code>PlayerModel</code> instance. */
	private static PlayerModel instance;

	/** List of players */
	private List<Player> players = new ArrayList<>();

	/** Current Player */
	private int currentPlayerIndex = 0;

	/**
	 * Private constructor.
	 */
	private PlayerModel()
	{}

	/**
	 * Return the single <code>PlayerModel</code> instance.
	 *
	 * @return instance
	 */
	public static PlayerModel getInstance()
	{
		if (instance == null)
			instance = new PlayerModel();

		return instance;
	}

	/**
	 * Add the player to the player list.
	 * 
	 * @param player
	 *            player
	 */
	public void addPlayer(Player player)
	{
		// Add player to the list
		players.add(player);
	}

	/**
	 * Return number of players.
	 * 
	 * @return number of players
	 */
	public int nbPlayers()
	{
		return players.size();
	}

	/**
	 * Return a player by his nickname.
	 * 
	 * @param nickname
	 *            player nickname
	 * @return player (<code>null</code> if not found)
	 */
	public Player getPlayer(String nickname)
	{
		// Search for all players
		for (Player player : players)
			// Check nickname
			if (player.getNickname().equalsIgnoreCase(nickname))
				return player;

		// Not found
		return null;
	}

	/**
	 * Return the next player.
	 * 
	 * @return player (<code>null</code> if not found)
	 */
	public Player nextPlayer()
	{
		if (this.players.size() <= 0)
			// Not Found
			return null;

		// Change player and return
		return this.players.get((currentPlayerIndex = (currentPlayerIndex + 1) % this.nbPlayers()));
	}

	/**
	 * Return the next player.
	 * 
	 * @return player (<code>null</code> if not found)
	 */
	public boolean allPlayerFinished()
	{
		for (Player p : players)
		{
			if (!p.hasFinished())
				return false;

		}
		return true;
	}

	/**
	 * Return the current player.
	 * 
	 * @return current player
	 */
	public Player getCurrentPlayer()
	{
		return players.get(currentPlayerIndex);
	}

	/**
	 * Return the players list.
	 * 
	 * @return players list
	 */
	public List<Player> getPlayers()
	{
		return players;
	}
}
